package com.asyf.demo.service.impl;

import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.util.PoiExcelGraphDataUtil;
import cn.afterturn.easypoi.util.PoiMergeCellUtil;
import cn.hutool.json.JSONUtil;
import com.asyf.demo.handler.ExcelDictHandlerImpl;
import com.asyf.demo.pojo.DataitemEntity;
import com.asyf.demo.pojo.DemandEntity;
import com.asyf.demo.pojo.DeptEntity;
import com.asyf.demo.pojo.SupMaterialEntity;
import com.asyf.demo.service.EasyPoiTemplateService;
import com.asyf.demo.demo.ZxingUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author yjz
 * @Date 2022/9/6 8:55
 */
@Slf4j
@Service
public class EasyPoiTemplateServiceImpl implements EasyPoiTemplateService {

    @Override
    public void exportTest(HttpServletResponse response, HttpServletRequest request) throws Exception {
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("test-" + System.currentTimeMillis() + ".xlsx", "UTF-8"));
        response.setCharacterEncoding("UTF-8");

        //模板参数
        TemplateExportParams params = new TemplateExportParams("templates/template.xlsx");
        Integer[] sheets = new Integer[]{0, 1};
        params.setSheetNum(sheets);//支持多个sheet
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", "李四");
        List<Map<String, String>> listMap = new ArrayList<Map<String, String>>();
        for (int i = 0; i < 4; i++) {
            Map<String, String> lm = new HashMap<String, String>();
            lm.put("id", i + 1 + "");
            lm.put("num", i + "");
            lm.put("email", i + "@email");
            listMap.add(lm);
        }
        map.put("maplist", listMap);

        //图片
        BufferedImage image = ZxingUtil.createImage("123qwe", "", false);
        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", byteArrayOut);

        //创建图片对象
        ImageEntity imageEntity = new ImageEntity(byteArrayOut.toByteArray(), 300, 300);

        //设置这个才能让图片显示出来，但是会默认合并了单元格
        imageEntity.setRowspan(2);
        imageEntity.setColspan(2);
        map.put("barcode", imageEntity);

        Workbook workbook = ExcelExportUtil.exportExcel(params, map);

        //手动画图片测试
        //drawPicTest(workbook, byteArrayOut);

        workbook.write(response.getOutputStream());
        workbook.close();

    }


    private void drawPicTest(Workbook workbook, ByteArrayOutputStream byteArrayOut) {
        Sheet sheet = workbook.getSheetAt(0);
        Drawing p = PoiExcelGraphDataUtil.getDrawingPatriarch(sheet);
        XSSFClientAnchor anchor = new XSSFClientAnchor(10, 10, 1010, 245,
                (short) 1, 1, (short) 2, 2); //后4个参数不能为空
        p.createPicture((ClientAnchor) anchor, workbook.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));

    }

    @Override
    public void foreach(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("test-" + System.currentTimeMillis() + ".xlsx", "UTF-8"));
        response.setCharacterEncoding("UTF-8");

        //模板参数
        TemplateExportParams params = new TemplateExportParams("templates/template2.xlsx");
        Integer[] sheets = new Integer[]{0, 1};
        params.setSheetNum(sheets);//支持多个sheet
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < 4; i++) {
            Map<String, Object> lm = new HashMap<>();
            lm.put("id", i + 1 + "");
            listMap.add(lm);
            //添加 details
            List<Map<String, Object>> details = new ArrayList<Map<String, Object>>();
            for (int j = 0; j < 4; j++) {
                Map<String, Object> m = new HashMap<>();
                m.put("id", i + 1 + "-详情" + j);
                details.add(m);
            }
            lm.put("details", details);
        }
        map.put("maplist", listMap);
        log.info(JSONUtil.toJsonStr(map));

        Workbook workbook = ExcelExportUtil.exportExcel(params, map);

        workbook.write(response.getOutputStream());
        workbook.close();
    }

    @Override
    public void foreach2(HttpServletResponse response, HttpServletRequest request) throws Exception {
        TemplateExportParams params = new TemplateExportParams(
                "templates/foreach_many.xlsx");

        Map<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < 400; i++) {
            Map<String, Object> testMap = new HashMap<String, Object>();

            testMap.put("id", "080101" + i);
            testMap.put("name", "大学" + i + "班");
            testMap.put("a1", getDeatil());
            testMap.put("a2", getDeatil());
            testMap.put("a3", getDeatil());
            testMap.put("sum1", "30" + i);
            testMap.put("sum2", "40" + i);
            mapList.add(testMap);
        }
        map.put("list", mapList);


        log.info(JSONUtil.toJsonStr(map));
        //本来导出是专业那个
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 1, 0, 4);
        File savefile = new File("C:/Users/yangjianzhang/Desktop/");
        if (!savefile.exists()) {
            savefile.mkdirs();
        }
        FileOutputStream fos = new FileOutputStream("C:/Users/yangjianzhang/Desktop/foreach_many_exprot.xlsx");
        workbook.write(fos);
        fos.close();
    }

    private Map<String, Object> getDeatil() {
        Map<String, Object> testMap = new HashMap<String, Object>();
        testMap.put("zero", (int) (Math.random() * 100));
        testMap.put("sixty", (int) (Math.random() * 100));
        testMap.put("eighty", (int) (Math.random() * 100));
        return testMap;
    }

    public static List<DemandEntity> getList() {
        List<DemandEntity> list = new ArrayList<DemandEntity>();
        DemandEntity de = new DemandEntity();
        de.setDeptName("省建设厅");
        de.setCode("审核转报-00180-000");
        de.setName("建筑业企业资质变更示例");
        de.setHandleTotal(3500L);
        de.setCategory(1);
        SupMaterialEntity sme = new SupMaterialEntity();
        sme.setMtype(1);
        sme.setLawType(1);
        sme.setSourceType(1);
        sme.setName("建筑业企业资质变更申请表");
        DataitemEntity dae = new DataitemEntity();
        dae.setName("企业营业执照号（五证合一社会信用号码）");
        List<DeptEntity> sdepts = new ArrayList<DeptEntity>();
        sdepts.add(new DeptEntity("省工商局"));
        dae.setSdepts(sdepts);
        sme.getDataitemList().add(dae);
        dae = new DataitemEntity();
        dae.setName("企业名称");
        sdepts = new ArrayList<DeptEntity>();
        sdepts.add(new DeptEntity("省工商局"));
        dae.setSdepts(sdepts);
        sme.getDataitemList().add(dae);
        dae = new DataitemEntity();
        dae.setName("资质证书编号");
        sdepts = new ArrayList<DeptEntity>();
        sdepts.add(new DeptEntity("省工商局"));
        sdepts.add(new DeptEntity("省省建设厅"));
        dae.setSdepts(sdepts);
        dae.setRemark("这就是生活啊");
        sme.getDataitemList().add(dae);
        de.getSupMaterialList().add(sme);

        sme = new SupMaterialEntity();
        sme.setMtype(1);
        sme.setLawType(1);
        sme.setSourceType(1);
        sme.setName("居民身份证");
        de.getSupMaterialList().add(sme);

        list.add(de);

        de = new DemandEntity();
        de.setDeptName("省建设厅");
        de.setCode("审核转报-00190-000");
        de.setName("建筑业企业资质变更示例无子项");
        de.setHandleTotal(6500L);
        de.setCategory(1);
        sme = new SupMaterialEntity();
        sme.setMtype(1);
        sme.setLawType(1);
        sme.setSourceType(1);
        sme.setName("建筑业企业资质变更申请表");
        dae = new DataitemEntity();
        dae.setName("企业营业执照号（五证合一社会信用号码）");
        sdepts = new ArrayList<DeptEntity>();
        sdepts.add(new DeptEntity("省工商局"));
        dae.setSdepts(sdepts);
        sme.getDataitemList().add(dae);
        dae = new DataitemEntity();
        dae.setName("企业名称");
        sdepts = new ArrayList<DeptEntity>();
        sdepts.add(new DeptEntity("省工商局"));
        dae.setSdepts(sdepts);
        sme.getDataitemList().add(dae);
        dae = new DataitemEntity();
        dae.setName("资质证书编号");
        sdepts = new ArrayList<DeptEntity>();
        sdepts.add(new DeptEntity("省工商局"));
        sdepts.add(new DeptEntity("省省建设厅"));
        dae.setSdepts(sdepts);
        dae.setRemark("这就是人生啊");
        sme.getDataitemList().add(dae);
        de.getSupMaterialList().add(sme);
        list.add(de);


        return list;
    }

    @Override
    public void foreach3(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("list", getList());
        TemplateExportParams params = new TemplateExportParams(
                "templates/nestedloop.xlsx");
        params.setDictHandler(new ExcelDictHandlerImpl());
        log.info(JSONUtil.toJsonStr(map));

        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        FileOutputStream fos = new FileOutputStream("C:/Users/yangjianzhang/Desktop/nestedLoopTest.xlsx");
        workbook.write(fos);
        fos.close();
    }
}
